package com.dxm.common.aspect;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.SourceLocation;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static java.util.stream.Collectors.joining;

@Aspect
@Component
@Slf4j
public class LogAspect {

    // @Pointcut("@annotation(com.dxm.common.annotation.Log)")
    @Pointcut(value = "(execution(* com.dxm.controller.*.*(..))))")
    public void pointcut() {

    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        //获取request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        StringBuilder sb = new StringBuilder();
        //拼接请求内容
        sb.append("\n请求路径:" + request.getRequestURL().toString() + "  " + request.getMethod() + "\n");
        //判断请求是什么请求
        if (request.getMethod().equalsIgnoreCase(RequestMethod.GET.name())) {
            Map<String, String[]> parameterMap = request.getParameterMap();
            Map<String, String> paramMap = new HashMap<>();
            parameterMap.forEach((key, value) -> paramMap.put(key, Arrays.stream(value).collect(joining(","))));
            sb.append("请求参数:" + JSON.toJSONString(paramMap));
        } else if (request.getMethod().equalsIgnoreCase(RequestMethod.POST.name())) {
            Object[] args = joinPoint.getArgs();
            StringBuilder stringBuilder = new StringBuilder();
            Arrays.stream(args).forEach(object -> stringBuilder.append(object.toString().replace("=",":")));
            if (stringBuilder.length() == 0){
                stringBuilder.append("{}");
            }
            sb.append("请求参数:" + stringBuilder.toString());
        }
        log.info(sb.toString());
    }


    @AfterReturning(value = "pointcut()", returning = "result")
    public void after(JoinPoint joinPoint, Object result) {
       log.info("\n返回结果：{}", JSONObject.toJSONString(result));
    }

    @AfterThrowing("pointcut()")
    public void afterThrow(JoinPoint joinPoint) {
        System.out.println("throw......");
    }


}

